import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../../toolkit/utils/encrypt_utils.dart';
import '../../../services/api_service.dart';

class SetPayPasswordLogic extends GetxController {
  final apiService = Get.find<ApiService>();

  var obscureNewPassword = true.obs;
  var obscureConfirmPassword = true.obs;

  final formKey = GlobalKey<FormState>();
  final newPasswordController = TextEditingController();
  final confirmPasswordController = TextEditingController();

  void onSubmit() async {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();

      EasyLoading.show(status: '正在设置支付密码...');

      var key = await apiService.getPayKey();
      if (key.isBlank ?? true) {
        EasyLoading.showError('获取密钥失败');
        return;
      }

      var newPassword = rsaEncrypt(key!, newPasswordController.text);

      var result = await apiService.setPayPwd(newPassword);
      EasyLoading.dismiss();
      if (result == null) {
        EasyLoading.showError('网络错误，请稍后重试！');
        return;
      }
      if (result.value['success'] == true) {
        Get.back();
        Get.snackbar('提示', '支付密码修改成功！');
      } else {
        EasyLoading.showError(result.value['error']['message']);
      }
    }
  }
}
